/*****************************************************************
*
*	Netcare Agent Project
*		Copyright(C) 2010, Wicresoft EKA. All Rights Reserved.
*
*	Authors:
*		TingRong Shi (trshi@wicresoft.com)
*
*	Part of the product code depends on gSOAP under GPL license
*		Copyright(C) 2000-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
*
*****************************************************************/

#include "DiskRelease.h"
#include "ns.h"

#ifdef WIN32
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include <fstream>
#else

#endif

#define RUNNING 1;
#define FREE 2;
#define WRONG 0;

NETCARE_AGENT;

CDiskRelease::CDiskRelease(void)
{

}

CDiskRelease::~CDiskRelease(void)
{

}

int CDiskRelease::DiskDefrag(int Commend)
{
#ifdef WIN32
	unsigned threadID;
	//WriteLog("1");
	switch(Commend)
	{
	case 0:
		//run defrag
		if(!GetThreadStat())
		{
			//WriteLog("2");
			hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DefragCmd, NULL, 0, NULL);
			if(hThread==NULL)
			{
				return WRONG;
			}
			else 
				return RUNNING;
		}	
		else
			return RUNNING;
		break;
	case 1:
		//check defrag statue
		if(GetThreadStat())
		{
			return RUNNING;
		}
		return FREE;
		break;
	default:	
		//wrong commend
		return WRONG;
		break;
	}
#else
	return FREE;
#endif
}

#ifdef WIN32
bool CDiskRelease::GetThreadStat()
{
	if(GetExitCodeThread(hThread, &dwExit))
	{
		if(dwExit == STILL_ACTIVE)
			return true;
		else if(dwExit == 0)
			return false;
	}
	else
		return false;
}
unsigned long __stdcall DefragCmd (void* lpThreadParameter)
{
	//WriteLog("3");
	wchar_t devstr[102];
	GetLogicalDriveStrings((sizeof devstr),devstr);
	int DriveNum = 0;
	wchar_t DriveName[4];
	char VolumeName[10]="defrag x:";
	for(; DriveNum<102&&devstr[DriveNum]!=0;DriveNum+=4)
	{
		DriveName[0]=devstr[DriveNum];
		DriveName[1]=devstr[DriveNum+1];
		DriveName[2]=devstr[DriveNum+2];
		DriveName[3]=devstr[DriveNum+3];
		UINT DriveType = GetDriveTypeW(DriveName);
		//WriteLog("4");
		if(DriveType==DRIVE_FIXED)
		{	
			VolumeName[7]=DriveName[0];
			//WriteLog("5");
			system(VolumeName);
			//system("notepad");

		}
	}
	
	return 0;
}

void WriteLog(char * log)
{
	ofstream f1("C:\\WINDOWS\\netcare\\log.txt");
	if(!f1)return;
	f1<<log<<endl;
	f1.close();
}
#else 

#endif


ENDNS ENDNS